import courseService from "../../service/courseService";
import { Request, Response } from 'express'
import { validateCreateForm, handleFormDataType } from "./validate";
import teacherService from "../../service/teacherService";
import selectLessonService from "../../service/selectLessonService";
import selectHistoriesService from "../../service/selectHistoriesService";

class CourseController {

  // 根据id进行查询
  async findById(req: Request, res: Response) {
    const { id } = req.params
    const course = await courseService.findById(id)
    if (course) {
      res.gsmd(course)
    } else {
      res.gem('该课程不存在！')
    }
  }

  // 创建课程
  async createCourse(req: Request, res: Response) {
    let form = req.body
    const msg = validateCreateForm(form)
    if (msg) return res.gem(msg)
    // 同专业下，不能出现同名课程
    const course = await courseService.findByCourseName(form.course_name)
    if (course && course.major_name === form.major_name) {
      return res.gem(`创建失败，【${form.major_name}】专业已存在【${form.course_name}】课程！`)
    }
    // 处理数据类型
    form = handleFormDataType(form)
    form.remaining = parseInt(form.num_limit)
    form.state = false // 课程创建默认为false
    // 保存课程表单数据到数据库
    const saveRes = await courseService.createCourse(form)
    if (!saveRes) return res.gem('创建失败！')
    res.gsm('创建成功')
  }

  // 修改课程
  async updateCourseInfo(req: Request, res: Response) {
    let form = req.body
    // console.log(form);
    // 同专业下，除了本身，不能出现同名课程
    const course = await courseService.findByCourseName(form.course_name)
    if (course && String(course.id) !== String(form.id) && course.major_name === form.major_name) {
      return res.gem(`创建失败，【${course.major_name}】专业已存在【${course.course_name}】课程！`)
    }
    // 根据id查找课程
    const courseWithId = await courseService.findById(form.id)
    // 如果教师修改了课程限制人数
    if (form.num_limit) {
      form.num_limit = Number(form.num_limit)
      if (form.num_limit < (courseWithId.num_limit - courseWithId.remaining)) {
        return res.gem(`限制人数错误，必须大于已选该课程人数，当前已选人数为：${courseWithId.num_limit - courseWithId.remaining}`)
      }
      form.remaining = form.num_limit - (courseWithId.num_limit - courseWithId.remaining)
    }
    form = handleFormDataType(form)
    // 修改信息
    // 先取出id，然后删除form中的id（数据库中为_id，这里为id，不一样会导致修改时添加id字段）
    const id = form.id
    delete form.id
    // 修改信息
    const result = await courseService.updateCourseInfo(id, form)
    if (result.affected < 0) return res.gem('课程修改信息失败！')
    const findResult = await courseService.findById(id)
    const teacher = await teacherService.findById(courseWithId.teacher_id)
    findResult.teacher_name = teacher.name
    res.gsmd(findResult, '课程信息修改成功！')
  }

  // 根据课程、教师、学院、专业名称模糊查询
  async findByNameKey(req: Request, res: Response) {
    const form = req.body
    let label = '', value = ''
    // 取出label和值（例如：course_name 和 ''）
    Object.keys(form).forEach(item => {
      if (item.includes('name')) {
        label = item
        value = form[item]
      }
    })

    const page_num = parseInt(req.body.page_num) || 1
    const page_size = parseInt(req.body.page_size) || 10
    const skip = (page_num - 1) * page_size

    const count = await courseService.findByNameKeyCount(label, value, form.teacher_id)
    const course = await courseService.findByNameKey(label, value, skip, page_size, form.teacher_id)
    // 根据教师id查询教师姓名
    for (let i = 0; i < course.length; i++) {
      const t = await teacherService.findById(course[i].teacher_id)
      Object.assign(course[i], { teacher_name: t.name })
    }
    if (!course) res.gem('查无数据！')
    res.gsmdl(count, course)
  }

  // 修改课程状态
  async updateCourseState(req: Request, res: Response) {
    const id = req.params.id
    const course = await courseService.findById(id)
    if (!course) return res.gem('该课程不存在！')
    const result = await courseService.udpateCourseState(id, !course.state)
    if (result.affected < 1) return res.gem('课程状态修改失败！')
    res.gsm('课程状态修改成功！')
  }

  // 删除课程
  async deleteCourse(req: Request, res: Response) {
    const { id } = req.params
    const course = await courseService.findById(id)
    if (!course) return res.gem('该课程不存在！')

    // TODO 删除课程
    const delRes1 = await courseService.deleteCourse(id)

    if (delRes1.affected >= 1) {
      
      // TODO 删除【学生角色】已选课程对应课程
      const selectRes = await selectLessonService.findByCid(id)
      selectRes && await selectLessonService.deleteManyByCid(id)
      
      // TODO 删除【学生角色】选课记录对应课程
      const historyRes = await selectHistoriesService.findByCid(id)
      historyRes && await selectHistoriesService.deleteManyByCid(id)

      return res.gsm('删除课程成功！')
    } else {
      return res.gem('删除课程失败！')
    }
  }

  // 学生的主修选修课程查询
  async findByStuUseNameKey(req: Request, res: Response) {
    const form = req.body
    let label = '', value = ''
    // 取出label和值（例如：course_name 和 ''）
    Object.keys(form).forEach(item => {
      if (item.includes('name')) {
        label = item
        value = form[item]
      }
    })
    const page_num = parseInt(req.body.page_num) || 1
    const page_size = parseInt(req.body.page_size) || 10
    const skip = (page_num - 1) * page_size
    form.type = parseInt(form.type)
    const course = await courseService.findByStuUseNameKey(label, value, skip, page_size, form.type)
    const count = await courseService.findByStuUseNameKeyCount(label, value, form.type)
    // 根据教师id查询教师姓名
    for (let i = 0; i < course.length; i++) {
      const t = await teacherService.findById(course[i].teacher_id)
      Object.assign(course[i], { teacher_name: t.name })
    }
    if (!course) res.gem('查无数据！')
    res.gsmdl(count, course)
  }
}

export default new CourseController()